import '@ant-design/compatible/assets/index.css';
import {
  CheckCircleOutlined,
  FormOutlined,
  LockOutlined,
  PhoneOutlined,
  SolutionOutlined,
  UserOutlined,
} from '@ant-design/icons';
import { Button, Card, Form, Input, message, Result, Steps } from 'antd';
import { FormInstance } from 'antd/lib/form';
import { connect } from 'dva';
import React, { Component } from 'react';
import Link from 'umi/link';
import md5 from '../../../../node_modules/js-md5';
import { encryptedData } from '@/utils/utils';
import { publicKey } from '../../../../public/global';
import styles from './index.less';
import router from 'umi/router';
import { emailTemplate, specicalChars } from "@/support/constant/common";
import { validateContinuousChar } from '@/utils/validator';

const FormItem = Form.Item;
const { Step } = Steps;
const mapStateToProps = (state: any) => ({
  // menu: state.menu,
  // loading: loading.effects['login/resetPassword'],
});

class ForgetPassword extends Component<any, any> {
  formRef = React.createRef<FormInstance>();

  constructor(props: any) {
    super(props);
    this.state = {
      current: 0, //  当前 step
      count: 60,
      countDown: 3,
      accountNameData: {},
      accountInfo: {},
      captchaLoadding: false,
      rules: {
        pwdStrategy: "",
        pwdStrategyDesc: "",
      }
    }
  }

  componentDidMount() {
    const { dispatch } = this.props;
    document.onkeydown = this.keydown;
    this.getRegular();
  }

  componentWillUnmount() {
    clearInterval(this.interval)
    clearInterval(this.timerCountDown)
    document.onkeydown = null  
  }

  keydown = (e: any) => {
    const { current } = this.state
    let currKey = 0;
    currKey = e.keyCode || e.which || e.charCode; // 支持IE、FF
    if (currKey == 13) {
      if (current === 0) {
        this.handleNext();
      }
      if (current === 1) {
        this.handleResetPwd()
      }
    }
  };

  //  获取密码校验规则（未登录，无法调接口）
  /* handleGetRules = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'extend/fetch',
      payload: { url: '/account/findpasswordstrategy' },
      callback: (response: any) => {
        this.setState({ rules: response.data });
      },
    });
  }; */

  //  倒计时3s，跳转登录页
  handleCountDown = () => {
    let countDown = 3
    this.timerCountDown = setInterval(() => {
      countDown--
      this.setState({ countDown });
      if (countDown < 0) {
        // clearInterval(this.timerCountDown)
        this.handleGoLogin()
      }
    }, 1000)
  }

  handleCountCode = () => {
    if(this.interval) clearInterval(this.interval);
    let count = 60;
    this.interval = setInterval(() => {
      count -= 1;
      this.setState({ count });
      if (count === 0) {
        clearInterval(this.interval);
      }
    }, 1000);
  }

  // 下一步
  nextStep = () => {
    const { current } = this.state;
    this.setState({ current: current + 1 }, () => {
      if (this.state.current === 1) {
        this.handleCountCode()
      }
      if (this.state.current === 2) {
        this.handleCountDown()
      }
    });
  };

  getCaptcha = () => {
    const { dispatch } = this.props;
    const { accountInfo: { accountName } } = this.state
    // this.setState({ captchaLoadding: true });
    dispatch({
      type: 'http/getData',
      payload: {  
        url: '/account/check',
        accountName,
      },
      callback: (res: any) => {
        this.handleCountCode();
      }
    })
  }

  //  点击下一步
  handleNext = () => {
    const { dispatch } = this.props;
    this.formRef.current
      ?.validateFields()
      .then((values) => {
        const { accountName } = values
        this.setState({
          accountInfo: {
            accountName
          }
        }, () => {
          //  进入下一步
          this.nextStep();
          this.handleCountCode();
        })
      })
  }

  //  重置密码
  handleResetPwd = () => {
    const { dispatch } = this.props;
    this.formRef.current
      ?.validateFields()
      .then((values) => {
        const { verifyCode, newAccountPwd } = values
        const { accountInfo: {accountName} } = this.state
        let obj = {
          accountName,
          currentPwd: encryptedData(newAccountPwd, publicKey),
          code: verifyCode
        }
        dispatch({
          type: 'http/postObjWithRes',
          payload: {
            url: '/account/codeReset',
            ...obj,
          },
          callback: (res: any) => {
            //  重置密码
            if (res.statusCode === '0') {
              this.nextStep()
              clearInterval(this.interval)
            }
          }
        })
      })
      .catch(err => {})
  }

  //  账号名称校验
  checkAccountName = async (rule: any, value: any) => {
    if(!value) {
      throw new Error('请输入账户名');
    }
    let res = await this.props.dispatch({
      type: 'account2/checkedAccount',
      payload: { accountName: value, type: emailTemplate.resetPassword }
    })
    if (res.statusCode === '0') {
        return Promise.resolve();
    }
    throw new Error(res.statusMessage);
  }

  //  校验密码
  checkPwd = (rule: any, value: any, callback: any) => {
    const {
      rules: { pwdStrategy, pwdStrategyDesc },
    } = this.state;
    const regex = new RegExp(pwdStrategy);
    // console.log(value, pwdStrategy, pwdStrategyDesc)
    if (value) {
      if (!regex.test(value)) {
        return Promise.reject(`请输入正确的密码，${pwdStrategyDesc}`);
      }else if(/([\dA-Za-z])\1{3,}/.test(value)) {
        return Promise.reject('禁止密码设置4位连续相同的字符');
      } else if(validateContinuousChar(value)) {
        return Promise.reject('禁止密码设置4位连续递增，递减的数字或字母');
      } else if(specicalChars.some(char => value.toLowerCase().indexOf(char.toLowerCase()) > -1 )) {
        return Promise.reject('禁止密码设置4位1qaz，2wsx，3edc，dfm，admin，dftc，dfrd等简单字符');
      }
    } else {
      return Promise.reject('请输入密码！');
    }
    return Promise.resolve();
  };

  //  校验再次输入密码
  checkRePwd = (rule: any, value: any, callback: any) => {
    const {
      rules: { pwdStrategy, pwdStrategyDesc },
    } = this.state;
    if (value) {
      const regex = new RegExp(pwdStrategy);
      if (!regex.test(value)) {
        return Promise.reject(`请输入正确的密码，${pwdStrategyDesc}`);
      }
    } else {
      return Promise.reject('请输入确认密码');
    }
    return Promise.resolve();
  };

  //  跳转登录页
  handleGoLogin = () => {
    clearInterval(this.timerCountDown)
    router.push('/user/login')
  }
  getRegular = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'http/getData',
      payload: {
        url: '/passwordstrategy/getregular/default'
      },
      callback: (res: any) => {
        this.setState({
          rules: res.data,
        })
      }
    });
  }
  render() {
    const { current, count, countDown, accountInfo, captchaLoadding } = this.state
    const captchaBtn = (
      <Button
        disabled={count}
        type="primary"
        style={{ width: '100%' }}
        onClick={() => this.getCaptcha()}
        loading={captchaLoadding}
      >
        {count ? `${count}s`: '验证码'}
      </Button>
    )
    const firstStep = (
      <>
      <div className={styles.promptText}></div>
      <div className={styles.formContent}>
        <FormItem
          name="accountName"
          label=""
          labelCol={{ span: 0 }}
          validateFirst={true}
          rules={[
            {
              required: true,
              message: '请输入账号名称'
            },
             {
              validateTrigger: ['onSubmit'],
              validator: this.checkAccountName
            }
          ]}
        >
          <Input
            prefix={<UserOutlined style={{ color: 'rgba(0,0,0,.25)' }} />}
            placeholder="请输入账号名称"
          />
        </FormItem>
        <Button
          type="primary"
          style={{ width: '100%' }}
          onClick={() => this.handleNext()}
        >
          下一步
        </Button>
      </div>
      </>
    )

    const secondStep = (
      <>
        <div className={styles.promptText}>
          验证码已发出至您账号绑定的邮箱，5分钟内有效，请注意查收！
        </div>
        <div className={styles.formContent}>
          <FormItem
            name="verifyCode"
            label=""
            labelCol={{ span: 0 }}
            rules={[{ required: true, pattern: /^[A-Za-z0-9]{4}$/, message: '请输入4位验证码！' }]}
          >
            <Input maxLength={4} placeholder="请输入验证码" addonAfter={captchaBtn} />
          </FormItem>
          <FormItem
            name="newAccountPwd"
            label=""
            // labelAlign="left"
            hasFeedback
            rules={[{ required: true, validator: this.checkPwd }]}
          >
            <Input.Password prefix={<LockOutlined />} minLength={8} maxLength={12} placeholder="请输入新登录密码" />
          </FormItem>
          <FormItem
            name="newAccountPwdCheck"
            label=""
            dependencies={['newAccountPwd']}
            hasFeedback
            rules={[
              // { required: true, validator: this.checkRePwd },
              { required: true, message: '请输入确认密码' },
              ({ getFieldValue }) => {
                return {
                    validator(_, value) {
                      if (!value || getFieldValue('newAccountPwd') === value) {
                        return Promise.resolve();
                      }
                      return Promise.reject(new Error('两次输入的密码不匹配！'));
                    },
                  }
                },
            ]}
          >
            <Input.Password prefix={<LockOutlined />} minLength={8} maxLength={12} placeholder="请再次输入登录密码" />
          </FormItem>
          <Button
            type="primary"
            style={{ width: '100%' }}
            onClick={() => this.handleResetPwd()}
          >
            下一步
          </Button>
        </div>
      </>
    )

    const items = [
      {
        title: '验证身份',
        content: firstStep,
        // description,
      },
      {
        title: '设置新密码',
        content: secondStep,
        // description,
      },
      {
        title: '重置成功',
        content: null,
        // description,
      },
    ];

    return (
      <div className={styles.wrapper}>
        <div className={styles.goLogin}>
          <span onClick={this.handleGoLogin}>
            <UserOutlined /> 登录
          </span>
        </div>
        <Card bordered={true} style={{ height: '100%' }}>
          {current !== 2 ? (
            <>
              <Steps current={current} style={{}} labelPlacement="vertical">
                {items.map((item, index) => (
                  <Step key={index} title={item.title} />
                ))}
              </Steps>
              <div className={styles.stepsContent}>
                <Form ref={this.formRef}>{items[current].content}</Form>
              </div>
            </>
          ): (
            <>
              <div className={styles.success}>
                <Result
                  className={styles.result}
                  status="success"
                  title="密码重置成功"
                  subTitle={`${countDown}s后跳转至登录页面`}
                  extra={[
                    <Button
                      ghost={true}
                      type='primary'
                      key="btnLogin"
                      onClick={() => {
                        this.handleGoLogin()
                      }}
                    >
                      重新登录
                    </Button>
                  ]}
                />
              </div>
            </>
          )}
        </Card>
      </div>
    )
  }
}
export default connect(mapStateToProps)(ForgetPassword);
